package com.si.anddos.tests;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import com.si.anddos.dpadapters.Account;
import com.si.anddos.library.main.factory.ServiceProviderFactory;
import com.si.anddos.library.provider.FileInfo;
import com.si.anddos.library.provider.ServiceProvider;
import com.si.anddos.library.provider.ServiceProviderAdapter;
import com.si.anddos.utils.FileSaver;

/**
 * 
 * @author Carlos Martinez
 */

public class ServiceProviderStopDownloadTest extends ServiceProviderAdapter {

	private long startPosition;
	FileSaver fileSaver = null;
	
	public static void main(String[] args) {
		
		new ServiceProviderStopDownloadTest().download();
	}
	
	public void download() {
		
		try {
			
			URL url = new URL("http://rapidshare.com/files/431610224/IMG_0171.JPG");
			
			Account account = new Account();

			account.setUserName("anddos5");
			account.setPassword("anddos3poi0");
			account.setService("rapidshare.com");
			
			ServiceProvider serviceProvider = ServiceProviderFactory.getProvider(url);
			
			serviceProvider.setServiceProviderListener(this);
			
			FileInfo fileInfo = serviceProvider.getFileInfo(url);
			
			fileSaver = new FileSaver(new File(System.getProperty("user.home"), serviceProvider.getFileInfo(url).getName()));
			
			if (fileSaver.length() >= fileInfo.getSize()) {
				
				System.out.println("Download is done!");
				
				return;
			}
			
			serviceProvider.setFileSaver(fileSaver);

			startPosition = fileSaver.length();
			
			fileSaver.setPosition(startPosition);
			
			serviceProvider.download(account, startPosition);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fileSaver != null) {
				try {
					fileSaver.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	@Override
	public void downloadStart(ServiceProvider provider) {

		System.out.println("Download did start: " + provider.getURL());
	}

	@Override
	public void downloadWait(ServiceProvider provider, int time) {
		
		System.out.println("Download will wait for " + time + " seconds.");
	}

	@Override
	public void downloadProgress(ServiceProvider provider, long size, long downloaded) {
		
		if (size != 0) {
			System.out.println("Downloaded " + ((100 * downloaded ) / size) + "%.");
		}
		
		if (downloaded - startPosition >= (100 * 1024)) {
			provider.stopDownload();
		}
	}

	@Override
	public void downloadFinish(ServiceProvider provider) {
		
		System.out.println("Download did finish");
	}

	@Override
	public void downloadFail(ServiceProvider provider, Throwable throwable) {
		
		System.out.println("Download did fail with error: " + throwable);
		
		throwable.printStackTrace();
	}

	@Override
	public void downloadStop(ServiceProvider provider) {
		
		System.out.println("Download did stop");
	}
}
